package longrise.phone.com.bjjt_henan.main;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.listview_library_refrush.PullToRefreshBase;
import com.longrise.android.listview_library_refrush.PullToRefreshListView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.Adapter.SelectCarAdapter;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;
import longrise.phone.com.bjjt_henan.widget.DealDialog;

/**
 * 选择查询的车辆列表
 * Created by Administrator on 2017/5/11.
 */
public class SelectCarView extends LFView implements ILSMsgListener {

    private Context mContext;

    private View mView;

    private PullToRefreshListView mListView;

    private SelectCarAdapter mAdapter;

    private EntityBean[] carBeans;

    private DealDialog dealDialog;

    private int type;

    private EntityBean curBean;

    private boolean isLoading = false;// 正在刷新

    private BaseApplication mApplication;

    public SelectCarView(Context context, EntityBean[] beans) {
        super(context);
        this.mContext = context;
        this.carBeans = beans;
        this.mApplication = ((MainActivity) context).getAppData();
    }

    public void setType(int type) {
        this.type = type;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter form = new FormParameter();
        form.setShowtitle(false);
        return form;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public void init() {
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_selectcar, null);
        if (mView == null) {
            return;
        }
        //标题栏
        TextView titleTV = (TextView) mView.findViewById(R.id.tv_title);
        mView.findViewById(R.id.hn_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnDestroy();
                closeForm();
            }
        });
        titleTV.setText(mContext.getResources().getString(R.string.select_car));
        mListView = (PullToRefreshListView) mView.findViewById(R.id.selectcar_lv);
        initRefreshView();
        mListView.getRefreshableView().setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        mAdapter = new SelectCarAdapter(mContext);
        mListView.setAdapter(mAdapter);
        mAdapter.setData(carBeans);

        this.addILSMsgListener(this);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 1) {
                    return;
                }
                curBean = carBeans[position - 1];
                String carno = curBean.getString("carno");
                String cartype = curBean.getString("cartype");
                String num = curBean.getString("identificationnum");
                if (TextUtils.isEmpty(num) || TextUtils.isEmpty(cartype) || TextUtils.isEmpty(carno)) {
                    showDealDialog();
                    return;
                }
                if (type == 0) {//违章查询需要发动机号
                    String engineno = curBean.getString("engineno");
                    if (TextUtils.isEmpty(engineno)) {
                        showDealDialog();
                        return;
                    }
                }
                if (type == 1) {//年检需要注册时间
                    String time = curBean.getString("registertime");
                    if (TextUtils.isEmpty(time)) {
                        showDealDialog();
                        return;
                    }
                }
                if (type == 0) {
                    SearchPeccancyView pecView = new SearchPeccancyView(mContext, curBean);
                    FrameworkManager.getInstance().showNewForm(mContext, pecView);
                } else if (type == 1) {
                    CarInspectView inspectView = new CarInspectView(mContext, curBean);
                    FrameworkManager.getInstance().showNewForm(mContext, inspectView);
                }
            }
        });
    }

    private void initRefreshView() {
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        // 刚拉时的提示
        mListView.getLoadingLayoutProxy().setPullLabel("加载列表数据...");
        // 正在刷新提示
        mListView.getLoadingLayoutProxy().setRefreshingLabel("正在载入...");
        // 拉倒一定高度的提示
        mListView.getLoadingLayoutProxy().setReleaseLabel("放开以刷新...");
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!isLoading) {
                    getBindData();
                    isLoading = true;
                }
            }
        });
    }

    //数据失败手动刷新
    private void getBindData() {
        try {
            String userId = mApplication.getKckpName();
            String token = mApplication.getToken();
            ApiImpI.getInstance(mContext.getApplicationContext()).bindState(userId, token,
                    new ApiImpI.RequestCallBack() {
                        @Override
                        public void onError(String error) {
                            isLoading = false;
                            if (null != mListView) {// 停止刷新
                                mListView.onRefreshComplete();
                            }
                            if (!TextUtils.isEmpty(error)) {
                                UiUtil.showToast(mContext, error);
                            }
                        }

                        @Override
                        public void onSuccess(Object result) {
                            isLoading = false;
                            if (mView == null) {
                                return;
                            }
                            if (null != mListView) {// 停止刷新
                                mListView.onRefreshComplete();
                            }
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                EntityBean bindData = bean.getBean("data");
                                if (null != bindData) {
                                    carBeans = bindData.getBeans("car");
                                    if (null != mAdapter) {
                                        mAdapter.setData(carBeans);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                }
                                //保存车辆和驾驶证的数据
                                String carInfo = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(bean);
                                PrefUtils.setString(mContext, "carinfo", carInfo);
                                LSMsgCall(102, "carinfo");
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDealDialog() {
        if (dealDialog == null) {
            dealDialog = new DealDialog(mContext);
            dealDialog.setInfo(R.string.bind_carinfo);
            dealDialog.setCancel("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dealDialog.dismiss();
                }
            });
            dealDialog.setConfirm("完善信息", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dealDialog.dismiss();
                    BindCarView bindcarview = new BindCarView(mContext, curBean);
                    FrameworkManager.getInstance().showNewForm(mContext, bindcarview);
                }
            });
        }
        dealDialog.show();
    }

    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public Object onLSMsg(int i, Object... objects) {
        switch (i) {
            case 102://重新获取绑定的数据
                EntityBean bean = (EntityBean) JSONSerializer.getInstance().DeSerialize(PrefUtils.
                        getString(mContext, "carinfo", null), EntityBean.class);
                EntityBean bindData = bean.getBean("data");
                if (null != bindData) {
                    carBeans = bindData.getBeans("car");
                    if (null != mAdapter) {
                        mAdapter.setData(carBeans);
                        mAdapter.notifyDataSetChanged();
                    }
                }
                break;
        }
        return null;
    }

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        mView = null;
        if (dealDialog != null) {
            dealDialog.dismiss();
            dealDialog = null;
        }
        if (null != mListView) {
            mListView.setAdapter(null);
            mListView.setOnItemClickListener(null);
            mListView = null;
        }
        removeILSMsgListener(this);
    }
}
